export default class PaoPao {
    private vx: number;
    private vy: number;
    private readonly radius: number;
    private readonly canvasWidth: number;
    private readonly canvasHeight: number;
    private ctx: CanvasRenderingContext2D;
    private readonly color: string;
    private isReady: boolean;
    private readonly friction: number;

    constructor(private x: number, private y: number, canvasWidth: number, canvasHeight: number, ctx: CanvasRenderingContext2D, color: string) {
        this.x = x;
        this.y = y;
        this.vx = 0
        this.vy = 0
        this.radius = 50;
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
        this.ctx = ctx;
        this.color = color || 'blue';
        this.isReady = false;
        //摩擦力
        this.friction = 0.9;
    }

    draw() {
        this.ctx.beginPath();
        this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        this.ctx.fillStyle = this.color;
        this.ctx.fill();
        this.ctx.strokeStyle = 'black';
        this.ctx.stroke();
    }

    move() {
        this.x += this.vx;
        this.vx = Math.max(-10, Math.min(this.vx * 1.5, 10));
        this.y += this.vy;

        if (this.x > this.radius && !this.isReady) {
            this.isReady = true;
        }
        if (!this.isReady) return;

        // 碰撞反弹
        if (this.x >= this.canvasWidth - this.radius || this.x <= this.radius) {
            this.vx = -this.vx;
        }
        if (this.y >= this.canvasHeight - this.radius || this.y <= this.radius) {
            this.vy = -this.vy;
        }

        // 摩擦力
        this.vx *= this.friction;
        this.vy *= this.friction;

        if(this.vx < 0.1 && this.vy < 0.1) {
            this.vx = 0;
            this.vy = 0;
        }
    }

    /**
     * 计算与指定点的距离
     */
    calculateDistanceWithPoint(x: number, y: number) {
        return Math.sqrt(
            (this.x - x) ** 2 + (this.y - y) ** 2
        );
    }

    /**
     * 设置位置
     */
    setPosition(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    /**
     * 获取位置
     */
    getPosition() {
        return {
            x: this.x,
            y: this.y
        }
    }
}